<?php

namespace App\Blocks;

use App\Models\Users;
use DB;
use App\Models\Goods;
use App\Models\GoodsImgs;
use App\Models\Categories;
use App\Models\Brand;
use App\Models\Crowd;
use App\Models\CrowdCategories;
use App\Models\GoodComment;
use App\Models\GoodCommentImage;

class GoodsBlock
{


    //商品列表
    public function Goods_list($data, $order, $pagination)
    {
        $goodsimgmodel = new GoodsImgs();
        $corwdmodel = new Crowd();
        $categoriesmodel = new Categories();
        $brandmodel = new Brand();
        $goodsmodel = new Goods();
        $crowd = new ArticleDataBlock();
        $page = !isset($pagination['page']) ? 1 : $pagination['page'];
        $pagesize = !isset($pagination['pagesize']) ? 5 : $pagination['pagesize'];

        $img_url = DB::table($goodsimgmodel->getTable())->select('id as uid','g_id','img_url as url')
            ->whereNull('deleted_at')
            ->get();

        $sql = Db::table($goodsmodel->getTable() . ' as a')
            ->select(
                'a.id as key',
                'a.inventory',
                'a.show_title',
                'a.name',
                'a.small_image',
                'a.producing_area',
                'a.unit',
                'a.stock_num',
                'a.slogan',
                'a.illustrate',
                DB::raw('round(sq_a.now_price / 100,2) as now_price'),
                DB::raw('round(sq_a.out_price / 100,2) as out_price'),
                DB::raw('round(sq_a.in_price / 100,2) as in_price'),
                'a.salenum',
                'a.status',
                'a.on_off_time',
                'a.created_at',
                'b.id as b_id',
                'c.id as c_id',
                'd.id as d_id', 'd.name as crowd_name'
            )->leftJoin($brandmodel->getTable() . ' as b', 'a.b_id', '=', 'b.id')
            ->leftJoin($categoriesmodel->getTable() . ' as c', 'a.c_id', '=', 'c.id')
            ->leftJoin($corwdmodel->getTable() . ' as d', 'a.crowd_id', '=', 'd.id')
            ->whereNull('a.deleted_at');
        $total = $this->like_select($sql, $data)->get()->count();

        if (isset($order)) {
            $field = explode("_", $order);
            $str = array_pop($field);
            $order_type = substr($str, 0, strlen($str) - 3);
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->orderBy(implode("_", $field), $order_type)->get();
        } else {
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->get();
        }

        foreach ($list as $key => $value){

            foreach (explode(',',$value->small_image) as $small_k => $small_key_v){
                $small_image[$small_k]['name'] = $small_key_v;
                $small_image[$small_k]['status'] = 'done';
                $small_image[$small_k]['uid'] = $small_k;
                $small_image[$small_k]['url'] = $small_key_v;
                $value->small_image = $small_image;
            }
            foreach (explode(',',$value->illustrate) as $k => $v){
                $illustrate[$k]['name'] = $v;
                $illustrate[$k]['status'] = 'done';
                $illustrate[$k]['uid'] = $k;
                $illustrate[$k]['url'] = $v;
                $value->illustrate = $illustrate;
            }

            foreach ($img_url as $imgs){
                if ($value->key == $imgs->g_id){
                    $value->img_url[] = $imgs;
                }
            }

        }
        $res = array(
            'list' => $list,
            'pagination' => array(
                'total' => $total,
                'pageSize' => (int)$pagesize,
                'current' => (int)$page
            ),
            'crowd_data' => $crowd->crowd_name(),
            'brand_data' => $this->brand_data(),
            'treeData' => $this->categories_list()
        );
        return $res;

    }

    private function like_select($sql, $data)
    {
        foreach ($data as $key => $value) {
            if ($value != '') {
                if (is_numeric($value)) {
                    $sql->where($key, $value);
                } else {
                    $sql->where('a.' . $key, 'like', '%' . $value . '%');
                }

            }
        }

        return $sql;
    }


    private function brand_data()
    {
        $brandmodel = new Brand();
        return Db::table($brandmodel->getTable())->select('id', 'c_id', 'name')->get();
    }

    //添加商品
    public function goods_add($goodsData,$goodsImgUrl)
    {
        DB::beginTransaction();
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImgs();
        try {
            $goodsID = DB::table($goodsModel->getTable())->insertGetId($goodsData);
            if (!$goodsID){
                DB::rollBack();
                return false;
            }

            if (count($goodsImgUrl)>0){
                foreach ($goodsImgUrl as $key => $item) {
                    $imgUrl[$key]['g_id'] = $goodsID;
                    $imgUrl[$key]['img_url'] = $item;
                    $imgUrl[$key]['created_at'] = date('Y-m-d H:i:s',time());
                }
                $img = DB::table($goodsImgModel->getTable())->insert($imgUrl);
                if (!$img){
                    DB::rollback();
                    return false;
                }
            }

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //删除商品
    public function good_del($id)
    {
        DB::beginTransaction();
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImgs();
        try {
            if( !DB::table($goodsModel->getTable())->where('id', $id)
                ->update(['deleted_at' => date('Y-m-d H:i:s', time())]) ){
                DB::rollBack();
                return false;
            }

            if( !DB::table($goodsImgModel->getTable())->where('g_id', $id)
                ->update(['deleted_at' => date('Y-m-d H:i:s', time())]) ){
                DB::rollBack();
                return false;
            }

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }

    }

    //修改商品
    public function good_update($goodsData,$ImgUrlData)
    {

        DB::beginTransaction();
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImgs();

        try {

            $goodsRes = DB::table($goodsModel->getTable())->where('id', $goodsData['id'])->update($goodsData);
            if (!$goodsRes){
                DB::rollBack();
            }

            if (!DB::table($goodsImgModel->getTable())->where('g_id',$goodsData['id'])
                ->update(['deleted_at'=>date('Y-m-d H:i:s',time())])){
                DB::rollBack();
                return false;
            }

            if (count($ImgUrlData)>0){



                if(!DB::table($goodsImgModel->getTable())->insert($ImgUrlData)){
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    //商品分类列表
    public function categories_list()
    {
        $categoriesmodel = new Categories();
        $data = Db::table($categoriesmodel->getTable())
            ->select('id', 'name', 'father_id', 'level')
            ->whereNull('deleted_at')
            ->get();
        $data = json_decode($data, true);
        $array = array();
        foreach ($data as $key => $value) {
            $array[$key]['title'] = $value['name'];
            $array[$key]['key'] = $value['id'];
            $array[$key]['level'] = $value['level'];
            $array[$key]['value'] = $value['id'];
            $array[$key]['father_id'] = $value['father_id'];
        }
        $res = $this->generateTree($array);
        return $res;
    }

    private function generateTree($array)
    {

        $items = array();
        foreach ($array as $value) {
            $items[$value['key']] = $value;
        }
        $tree = array();
        foreach ($items as $key => $value) {
            if (isset($items[$value['father_id']])) {
                $items[$value['father_id']]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    //品牌列表
    public function brand_list($data, $order, $pagination)
    {
        $categoriesmodel = new Categories();  //分类 b
        $brandmodel = new Brand();  //品牌 a
        $page = !isset($pagination['page']) ? 1 : $pagination['page'];
        $pagesize = !isset($pagination['pagesize']) ? 5 : $pagination['pagesize'];
        $sql = DB::table($brandmodel->getTable() . ' as a')
            ->select('a.id as key', 'a.name', 'b.name as c_name', 'a.created_at', 'c_id')
            ->leftJoin($categoriesmodel->getTable() . ' as b', 'a.c_id', '=', 'b.id')
            ->whereNull('a.deleted_at');
        $total = $this->like_select($sql, $data)->get()->count();
        if (isset($order)) {
            $field = explode("_", $order);
            $str = array_pop($field);
            $order_type = substr($str, 0, strlen($str) - 3);
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->orderBy(implode("_", $field), $order_type)->get();
        } else {
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->get();
        }
        $res = array(
            'list' => $list,
            'pagination' => array(
                'total' => $total,
                'pageSize' => (int)$pagesize,
                'current' => (int)$page
            ),
            'treeData' => $this->categories_list()
        );
        return $res;
    }

    //品牌删除
    public function brand_del($id)
    {
        $brandmodal = new Brand();
        $res = DB::table($brandmodal->getTable())->where('id', $id)->update(['deleted_at' => date('Y-m-d H:i:s', time())]);
        return $res;
    }

    //品牌添加
    public function brand_Add($data)
    {
        $brandmodal = new Brand();
        $res = DB::table($brandmodal->getTable())->insert($data);
        return $res;
    }

    //品牌修改
    public function brand_update($id, $data)
    {
        $brandmodal = new Brand();
        $res = DB::table($brandmodal->getTable())->where('id', $id)->update($data);
        return $res;
    }

    //分类列表
    public function cat_list($data, $pagination, $order)
    {
        $page = !isset($pagination['page']) ? 1 : $pagination['page'];
        $pagesize = !isset($pagination['pagesize']) ? 5 : $pagination['pagesize'];
        $catemodal = new Categories();
        $sql = DB::table($catemodal->getTable() . ' as a')
            ->select(
                'a.id as key',
                'a.name',
                'a.level',
                'a.father_id',
                'created_at',
                DB::raw("(select `name` from `sq_categories` where `id` = sq_a.father_id) as father_name "))
                ->whereNull('a.deleted_at');
        $total = $this->like_select($sql, $data)->get()->count();

        if (isset($order)) {
            $field = explode("_", $order);
            $str = array_pop($field);
            $order_type = substr($str, 0, strlen($str) - 3);
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->orderBy(implode("_", $field), $order_type)->get();
        } else {
            $list = $this->like_select($sql, $data)->offset(($page - 1) * $pagesize)->limit($pagesize)->get();
        }
        $res = array(
            'list' => $list,
            'pagination' => array(
                'total' => $total,
                'pageSize' => (int)$pagesize,
                'current' => (int)$page
            ),
            'catedata' => $this->catedata(),
        );
        return $res;
    }

    private function catedata()
    {
        $catemodel = new Categories();
        $data = array();
        $sql = DB::table($catemodel->getTable())->select('id', 'name', 'level', 'father_id')->where('level', '<', 3)->get();
        $sql = json_decode(json_encode($sql), true);
        $array = array();
        foreach ($sql as $key => $value) {
            $array[$key]['title'] = $value['name'];
            $array[$key]['key'] = $value['id'];
            $array[$key]['level'] = $value['level'];
            $array[$key]['value'] = $value['id'];
            $array[$key]['father_id'] = $value['father_id'];
        }
        foreach ($array as $key => $value) {
            $data[$value['key']] = $value;
        }
        $tree = array();
        foreach ($data as $k => $v) {
            if (isset($data[$v['father_id']])) {
                $data[$v['father_id']]['children'][] = &$data[$k];
            } else {
                $tree[] = &$data[$k];
            }
        }
        return $tree;
    }

    //删除分类
    public function cate_del($id)
    {
        $catemodel = new Categories();
        $goods = new Goods();
        $where = $this->get_category($id);

        DB::beginTransaction();
        try {
            $res1 =   DB::table($catemodel->getTable())->whereIn('id', $where)->update(['deleted_at' => date('Y-m-d H:i:s', time())]);
            if ($res1 == false) {
                return false;
            }

            if (DB::table($goods->getTable())->whereIn('c_id',$where)->first()){
                $status = DB::table($goods->getTable())->whereIn('c_id', $where)->update(['deleted_at' => date('Y-m-d H:i:s', time())]);
                if ($status == false) {
                    DB::rollBack();
                    return false;
                }
            }


            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    private function get_category($id)
    {
        $cate = new Categories();
        if (is_array($id)){
            $ids = $id;
        }else{
            $ids = [$id];
        }
        $cate_data = DB::table($cate->getTable())->select('id', 'father_id')->get();
        $cate_data = json_decode(json_encode($cate_data), true);
        foreach ($cate_data as $key => $value) {
            $is_in = in_array($value['father_id'],$ids);
            if ($is_in){
                $ids[] = $value['id'];
            }
        }
        return $ids;
    }

    //修改分类
    public function cate_update($id, $data)
    {
        $catemodel = new Categories();
        $res = DB::table($catemodel->getTable())->where('id', $id)->update($data);
        return $res;
    }

    //添加分类
    public function cate_insert($data)
    {
        $catemodel = new Categories();
        $arr = array();
        if ($data['c_id'] == 0) {
            $arr['name'] = $data['name'];
            $arr['father_id'] = 0;
            $arr['level'] = 1;
        } else {
            $arr['name'] = $data['name'];
            $arr['father_id'] = $data['c_id'];
            $level = DB::table($catemodel->getTable())->where('id', $data['c_id'])->pluck('level');
            $level = json_decode(json_encode($level), true);
            $arr['level'] = $level[0] + 1;
        }
        $arr['created_at'] = date('Y-m-d H:i:s', time());
        $res = DB::table($catemodel->getTable())->insert($arr);
        return $res;
    }

    //商品列表
    public function apiGoodList($crowd_id){
        $goods = new Goods();
        $sql = DB::table($goods->getTable())
            ->select(
                'id',
                'crowd_id',
                'small_image',
                'salenum',
                DB::raw('round(out_price / 100, 2) as out_price'),
                'name',
                'inventory',
                'on_off_time',
                'created_at')
            ->where('crowd_id',$crowd_id)
            ->whereNull('deleted_at')
            ->get();
        return $sql;
    }

    //激光群商品列表
    public function Api_jg_goods_list($jg_id){
        $goods = new Goods();
        $crowd = new Crowd();
        $crowd_id = DB::table($crowd->getTable())->select('id')->where('jg_im_gid',$jg_id)->first();
        if (!$crowd_id){
            return false;
        }
        $sql = DB::table($goods->getTable())->select('id','crowd_id','small_image','salenum','out_price','name')
            ->where('crowd_id',$crowd_id->id)->whereNull('deleted_at')->get();
        return $sql;
    }

    //商品详情
    public function Api_goods_details($id){
        $goodsModel = new Goods();
        $goodsImgModel = new GoodsImgs();
        $userModel = new Users();
        $crowdModel = new Crowd();
        $commentModel = new GoodComment();
        $commentImageModel = new GoodCommentImage();
        $content = DB::table($goodsModel->getTable().' as g')
            ->select(
              'g.id',
              'c.name as crowd_name',
              'c.id as crowd_id',
              'g.show_title',
              'g.name',
              'g.producing_area',
              'g.unit',
              'g.salenum',
              'g.slogan',
              'g.illustrate',
              DB::raw('round(sq_g.now_price / 100, 2) as now_price'),
              DB::raw('round(sq_g.out_price / 100, 2) as out_price')
            )
            ->leftJoin($crowdModel->getTable().' as c','g.crowd_id','=','c.id')
            ->where('g.id',$id)->first();
        if (empty($content)){
            return [];
        }
        $comment = DB::table($commentModel->getTable().' as c')
            ->select('c.id','c.star','c.content','c.goods_name','u.nick_name','u.headimgurl','c.create_time')
            ->leftJoin($userModel->getTable().' as u','c.u_id','=','u.id')
            ->where('c.goods_id',$id)
            ->get();

        $commentId = [];
        foreach ($comment as $value){
            $value->img_url = [];
            $commentId[] = $value->id;
        }

        $commentImg = DB::table($commentImageModel->getTable())->select('comment_id','img_url')->whereIn('comment_id',$commentId)->get();
        foreach ($comment as $value) {

            foreach ($commentImg as $item) {
                if ($value->id == $item->comment_id){
                    $value->img_url[] = $item->img_url;
                }
            }
        }

        $img = DB::table($goodsImgModel->getTable())->select('img_url')->where('g_id',$id)->whereNull('deleted_at')->get();
        $content->img = $img;
        $content->evalue_content = $comment;
        $content->illustrate = explode(',',$content->illustrate);
        return $content;
    }


    public function Api_brand_list(){
        $brand = new Brand();
        $cate = new Categories();
        $res = DB::table($brand->getTable().' as a')->select('a.id','a.c_id','a.name','b.name as c_name')
            ->leftJoin($cate->getTable().' as b','a.c_id','=','b.id')
            ->get();
        return $res;
    }
    //群商品分类
    public function crowd_cate($id){
        $cate = new CrowdCategories();
        return DB::table($cate->getTable())->select('id','crowd_id','name')->where('crowd_id',$id)->get();
    }

    //群商品分类商品
    public function crowd_cate_goods($id){
        $goods = new Goods();
        return DB::table($goods->getTable())->select('id','crowd_id','name','small_image','out_price')->where('cate_id',$id)->get();
    }

//推荐商品列表

    public function commentGoodsList($crowd_id){
        $goods = new Goods();
        $sql = DB::table($goods->getTable())
            ->select('id','crowd_id','small_image','salenum','out_price','name','inventory','on_off_time','created_at')
            ->where('crowd_id',$crowd_id)
            ->whereNull('deleted_at');
        return $sql;
    }
    public function commentList($search, $page, $pageSize){
        $sql = $this->commentGoodsList($search);

        $list = $sql->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('created_at', 'desc')
            ->get();

        return $list;
    }

    public function commentListPagination(array $search, int $page = 1, int $pageSize = 20){
        $sql = $this->apiGoodList($search['crowd_id']);
        return [
            'total' => $sql->count(),
            'pageSize' => $pageSize,
            'current' => $page,
        ];
    }
}
